package com.aofeng.hybrid.service;

import android.content.Context;
import com.aofeng.hybrid.orm.JSonMapConverter;
import com.aofeng.hybrid.util.CommUtil;
import com.aofeng.hybrid.util.ExpressionHelper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 业务服务
 * Created by LGY on 2016-07-04.
 */
public class LogicService extends GenericService {
    private static final Logger log = LoggerFactory.getLogger(LogicService.class);
    public LogicService(Context context) {
        super(context);
        services.put("log", log);
        EntityService entityService = new EntityService(context);
        SqlService sqlService = new SqlService(context);
        services.put("entity", entityService);
        services.put("sql", sqlService);
        services.put("logic", this);
        RestService restService = new RestService(context);
        services.put("rest", restService);
    }

    /**
     * 业务服务入口
     * @param json 格式: {alias:alias, json:{}}
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject action(JSONObject json){
        JSONObject result = new JSONObject();
        try {
            result.put("code", 500);
            result.put("data", "不可处理异常。");
            Object obj = run(json.getString("alias"), json.getJSONObject("data"));
            String s = String.valueOf(obj);
            result.put("code", 200);
            result.put("data", s);
            return result;
        } catch(Exception e) {
            try {
                result.put("code", 500);
                result.put("data", e.getMessage());
                return result;
            } catch (Exception ex) {
                //suck
                return result;
            }
        }
    }


    /**
     * 执行业务
     * @param alias 业务模块名称
     * @param json  业务参数对象
     */
    public Object run(String alias, JSONObject json) throws Exception {
        // 获取业务代码
        String path = LogicMapper.getSql(context,alias);
        String text = CommUtil.readFile(CommUtil.getFilePath(context) + "logics/" + path);
        Map<String, Object> data = JSonMapConverter.toMap(json);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data", data);
        Iterator<String> itr = services.keySet().iterator();
        //注入服务
        while(itr.hasNext()) {
            String key = itr.next();
            params.put(key, services.get(key));
        }
        Object result = ExpressionHelper.run(text, params);
        return result;
    }
}
